/**
 * kl yy-ds @2021
 */
package com.cxps.cloud.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传下载工具类
 *
 * @author YouCai.Liu
 * @since 2021/10/21
 * ...
 */
@Slf4j
public class UploadAndDownloadUtils {

    /**
     * 上传
     *
     * @param file           要上传的文件
     * @param exportLocation 上传文件的位置
     * @return
     * @throws IOException
     */
    public static Map<String, Object> upload(MultipartFile file, String exportLocation) throws IOException {
        // 返回参数
        Map<String, Object> map = new HashMap<>();

        // 获取上传的文件真实名称
        String fileRealName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileRealName.substring(fileRealName.lastIndexOf("."));
        // 给文件重命名，防止覆盖
        String timeMillis = IdUtils.generateId();
        String newFileName = timeMillis + suffix;
        // 生成新文件
        File newFile = new File(exportLocation + newFileName);

        // 上传
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = file.getInputStream();
            // 判断目录是否存在，不存在创建
            if (null != newFile.getParentFile() && !newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            outputStream = new FileOutputStream(newFile);
            IOUtils.copy(inputStream, outputStream);
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭文件操作流异常：" + ExceptionUtils.getStackTrace(e));
            }
        }

        // 返回图片信息
        map.put("fid", timeMillis);
        map.put("fileName", newFileName);
        map.put("filePath", exportLocation);
        map.put("fileRealName", fileRealName);
        map.put("fileSuffix", suffix);
        map.put("fileSize", file.getSize());
        return map;
    }

    /**
     * 下载
     *
     * @param filePath     文件的路径 = 文件路径+文件名
     * @param realFileName 文件的真实名
     * @param response     响应
     */
    public static void download(String filePath, String realFileName, HttpServletResponse response) {
        // 获取输入输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 读取要下载的文件
            inputStream = new FileInputStream(filePath);
            outputStream = response.getOutputStream();
            // 根据文件扩展名设置对应ContentType
            response.setContentType("application/x-msdownload; charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(realFileName, "UTF-8"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            log.error("文件操作异常：" + ExceptionUtils.getStackTrace(e));
            throw new IllegalArgumentException("文件操作异常！");
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭文件操作流异常：" + ExceptionUtils.getStackTrace(e));
            }
        }
    }

}
